# -*- coding: utf-8 -*-
"""
Formats HTML mail.
"""
import os.path
import mercurial.util as mercutil

_HTML_ESCAPE_TABLE = {
    "&": "&amp;",
    '"': "&quot;",
    "'": "&apos;",
    ">": "&gt;",
    "<": "&lt;",
}

def html_escape(text):
    """Produces HTML-escaped test."""
    return "".join(_HTML_ESCAPE_TABLE.get(c, c) for c in text)

class HtmlFormatter: #pylint: disable-msg=R0903
    """ Formats email to HTML format from processor list."""
    MAX_LEN = 120
    COLORS = [ "#e0e0e0", "#ffffff"]

    def __init__(self, title, repos):
        """ Creates formatter.
        
        title: title of the email
        repos: list of repository processors
        """
        self._title = title
        self._repos = repos
        self._current_repo = None
        self._index = 0
 
    def _process_line(self, line):
        """
        Processes single line from input replacing 
        @title with repository title
        and @rows with content of the changes for repository.
        """
        if "@title" in line:
            if self._current_repo.weburl is None:
                title = self._current_repo.title
            else:
                title = '<a href="' + self._current_repo.weburl + '">'\
                     + html_escape(self._current_repo.title) + '</a>'
            return line.replace("@title", title)
        elif "@rows" in line:
            text = ""
            for i in self._current_repo.changes:
                longfiles = i.files
                shortfiles = mercutil.ellipsis(longfiles, self.MAX_LEN)
                if (len(longfiles) != len(shortfiles)):
                    files_table = '<td title="' + \
                        longfiles.replace('"', "'") + '">'
                else:
                    files_table = '<td>'
                longdesc = i.comment
                shortdesc = mercutil.ellipsis(longdesc, self.MAX_LEN)
                if (len(longdesc) != len(shortdesc)):
                    desc_table = '<td title="' + \
                        longdesc.replace('"', "'") + '">'
                else:
                    desc_table = '<td>'
                if i.link is None:
                    rev = str(i.rev)
                else:
                    rev = '<a href="' + i.link + '">' + \
                        str(i.rev) + '</a>'         
                text = text + \
                '<tr style="color: #000000; background-color: ' + \
                self.COLORS[self._index] + '">' + \
                '<td> ' + rev + '</td>' + \
                '<td>' + i.user + '</td>' + \
                '<td nowrap>' + str(i.date) + '</td>' + \
                files_table + html_escape(shortfiles) + '</td>' + \
                desc_table + html_escape(shortdesc) + '</td>' + \
                '</tr>\n'
                self._index = (self._index + 1) % 2
            return line.replace("@rows", text)
        else:
            return line
        
    def _process_page_line(self, line):
        """
        Processes all lines replacing @title with title of the mail
        and @repos with list of repositories to be sent in this mail
        """
        if "@title" in line:
            return line.replace("@title", html_escape(self._title))
        elif "@repos" in line:
            text = ""
            for i in self._repos:
                self._index = 0
                if len(i.changes) != 0:
                    self._current_repo = i
                    text = text + self._html_format_repo()
            return line.replace("@repos", text)
        else:
            return line

    def _html_format_repo(self):
        """
        Formats single repository in HTML form from single_repo_template.html
        """
        the_file = open(os.path.join(os.path.dirname(__file__), \
                                     "single_repo_template.html"), "rt")
        try:
            lines = the_file.readlines()
        finally:
            the_file.close()
        newlines = [self._process_line(line) for line in lines]
        return "\n".join(newlines)

    def html_format_page(self):
        """ Formats current repository to html page from page template."""
        the_file = open(os.path.join(os.path.dirname(__file__), \
                                     "page_template.html"), "rt")
        try:
            lines = the_file.readlines()
        finally:
            the_file.close()
        newlines = [self._process_page_line(line) for line in lines]
        return "\n".join(newlines)
